var newTask = new Object();
var contacts;
var taskList;
var lastTaskTitle;

function loadTaskList() {
    $("#page-wrapper").load("parts/parts.tasklist.html");
}
function warn(msg) {
    alert(msg);
}

function htmlEncode(value) {
    if (value) {
        return jQuery('<div />').text(value).html();
    } else {
        return '';
    }
}

function htmlDecode(value) {
    if (value) {
        return $('<div />').html(value).text();
    } else {
        return '';
    }
}

function getJson(operation, successCallback, errorCallback) {
    $.ajax({
        method: 'POST',
        url: 'Gate',
        dataType: 'json',
        data: { req: JSON.stringify(operation) },
        success: function (data) {
            if (successCallback) successCallback(data)
        },
        error: function (xhr, status, err) {
            if (errorCallback) errorCallback(status, err);
        }
    });
    // $.getJSON('Gate', { req: JSON.stringify(operation) }, function (data) {
    //     callback(data);
    // });
}

function getJsonSync(operation, successCallback, errorCallback) {
    $.ajax({
        async: false,
        method: 'POST',
        url: 'Gate',
        dataType: 'json',
        data: { req: JSON.stringify(operation) },
        success: function (data) {
            if (successCallback) successCallback(data)
        },
        error: function (xhr, status, err) {
            if (errorCallback) errorCallback(status, err);
        }
    });
    // $.getJSON('Gate', { req: JSON.stringify(operation) }, function (data) {
    //     callback(data);
    // });
}


$(document).ready(function () {
    var op = createOperation('getContacts');
    getJson(op, function (data) {
        if (data.status == 0) {
            contacts = data.entity;
            //alert (JSON.stringify(data));
            var us = new userSelector('treeview-checkable', contacts);
            us.setData(contacts);
            us.setUserTree('treeview-checkable');
            us.onNodeSelected = function (event, node) {
                $("#targetUser").html(node.text);
                newTask.implementId = node.id;
                $("#userbook").hide();
            }
            us.show();
        }
        else alert(data.message);
    });

    getTaskList();

    $("#userbook").click(function (e) {
        e.stopPropagation();
    });
    $(document).click(function (event) {
        $("#userbook").hide();
        $("#addExeDiv").hide();
        $("#addRdrDiv").hide();
    });
    $("#targetUser").click(function (e) {
        e.stopPropagation();
        $("#userbook").show();
    });
    $("#newTaskTitle").keypress(function (ev) {
    	//alert("回车:keyCode="+ev.keyCode+"key="+ev.key);
        if (ev.keyCode == 13) {
        	alert("判断为回车键");
            if ($(this).val() == "") {
                return;
            }
            if ($(this).val() == lastTaskTitle) {
                warn("请勿重复创建任务！");
                $(this).val("");
                return;
            }
            newTask.userId = 0;
            newTask.title = $(this).val();
            newTask.deadline = $("#newTaskDate").val();
            getJson(createOperation('createTask', newTask), function (data) {
                if (data.status == 0) {
                    //getTaskList();

                    addNewTaskNode(correctTaskItem(data.entity), $("#taskListTable").DataTable());
                    lastTaskTitle = data.entity.task.title;
                    $("#newTaskTitle").val("");
                }
                else warn(data.message);
            }, function (status, err) {
                warn("REQ STAT=" + status + "\nERR:" + err);
            });
        }
    });
});

function addNewTaskNode(t, table) {
    //t = new Task from server response.
    //table = target table;
    if (!t || !table) {
        warn("new task node error. t=" + t + " table=" + table);
        return;
    }
    var rowNode = table.row.add(t).draw().node();
    table.order([5, 'desc']).draw();
    $(rowNode).css('color', 'red').animate({ color: 'black' });

}

function createOperation(op, obj) {
    var oper = new Object();
    oper.operation = op;
    oper.jsonObject = obj || { 'na': 'na' };
    return oper;
}

function correctTaskItem(t) {
    if (t) {
        if (t.deadLine == undefined)
            t.deadLine = null;
    }
    return t;
}

function getTaskList() {
    var op = createOperation('getTaskList');
    getJson(op, function (data) {
        if (data.status == 0) {
            taskList = data.entity;
            //showTable(prepareTaskTable(taskList));
            for (var i in taskList) {
                correctTaskItem(taskList[i].task);
            }
            showTable(taskList);
        }
    });
}

function prepareTaskTable(list) {
    var tasktable = new Array();
    for (var i = 0; i < list.length; i++) {
        var t = list[i].task;//object
        t.ownerName = list[i].owner.name;
        tasktable.push(t);
    }
    return tasktable;
}
function prepareTaskTableNode(task) {

}
function showTable(data) {
    $.fn.dataTable.ext.errMode = 'none';
    var taskTable = $('#taskListTable').DataTable({
    	"autoWidth":false,
        "data": data,
        "columns": [{
            "data": 'task.completion',
            "width": "16px",
            "orderable": false,
            "render": function (data, type, row, meta) {
                if (type == "display") {
                    if (data >= 100) {
                        //alert(JSON.stringify(row));
                        return '<input type="checkbox" class="myCheck" checked="checked" id="c' + row.task.id + '"><label for="c' + row.task.id + '"></label>';
                    }
                    str = '<input type="checkbox" class="myCheck" id="c' + row.task.id + '"><label for="c' + row.task.id + '"></label>';
                    return str;
                }
                return data;
            }
        },
        {
            "data": 'task.title',
            "render": function (data, type, row, meta) {
                if (type === "display") {
                    return '<a class="taskListTitle" id="t' + row.task.id + '">' + htmlEncode(data) + '</a>';
                }
                return data;
            }
        },
        {
            "data": 'task.completion',
            "width": '120px',
            "render": function (data, type, row, meta) {
                var realComp;
                realComp = data > 100 ? 100 : data;
                if (type === "display") {
                    return '<div class="progress" style="margin-bottom:0;height:16px"><div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="' + realComp + '" aria-valuemin="0" aria-valuemax="100" style="line-height:16px;height:16px;width: ' + realComp + '%;">' + realComp + '%</div></div>';
                }
                return realComp;
            }
        },
        {
            "data": 'owner.name',
            "width": '100px'

        },
        {
            "data": 'task.deadLine',
            "width": '120px'
        },
        {
            "visible": false,
            "data": 'task.createTime'
        }
        ],
        "order": [4, 'asc'],
        "oLanguage": {//语言设置  
            "sLengthMenu": "每页显示 _MENU_ 条记录",
            "sZeroRecords": "没有检索到数据",
            "sInfo": "当前显示 _START_ 到 _END_ 条，共 _TOTAL_ 条记录",
            "sInfoEmtpy": "没有数据",
            "sProcessing": '<i class="fa fa-coffee"></i> 正在加载数据...',
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "<span class=\"fa fa-chevron-left\">",
                "sNext": "<span class=\"fa fa-chevron-right\">",
                "sLast": "尾页"
            },
            "sSearch": "搜索 "
        },
        "drawCallback": function (settings) {
            $(".myCheck").click(data, function (ev) {
                ev.preventDefault();
                var tId = $(this).prop("id").substr(1);
                if ($(this).prop("checked")) {
                    setCompletion(tId, 1000, function (data) {
                        $("#c" + data.entity.id).prop("checked", true);
                    });
                }
                else (setCompletion(tId, -1, function (data) {
                    $("#c" + data.entity.id).prop("checked", false);
                }));
            });
            $(".taskListTitle").click(data, function (ev) {
                var tId = $(this).prop("id").substr(1);
                showTaskDetail(tId);
            });
        }
    });

}
function setCompletion(tId, comp, callback) {
    op = createOperation('setCompletion', { taskId: tId, completion: comp });
    $.getJSON("Gate", { req: JSON.stringify(op) }, function (data) {
        callback(data);
    });
}
function showTaskDetail(id) {
    //$("#modalTask").modal('show');
    $("#page-wrapper").load("parts/voteManageEdit.html", function () {
        var task;
        var tId = id;
        var view;


        getTask(tId, true);

        //获取任务详情
        function getTask(tId, ifRender) {
            var request = createOperation('getTaskDetail', { id: tId });
            $.getJSON("Gate", { req: JSON.stringify(request) }, function (data) {
                task = data.entity;
                if (ifRender) renderTaskView();
            });
            //task = { "owner": { "id": 0, "account": "18906414271", "passwd": "123456", "name": "张金钊", "teamId": 3, "isManager": 1, "phone": "18906414271", "email": "18906414271@189.cn", "sex": "男" }, "subTaskList": [{ "owner": { "id": 1, "account": "18906414263", "passwd": "123456", "name": "张金钊", "teamId": 82, "isManager": 0, "phone": "18906414263", "email": "18906414263@189.cn", "sex": "男" }, "subTaskList": [], "completion": 0, "description": "显示当前登录用户任务详情", "emergency": 0, "updateTime": "Sep 5, 2017 10:14:07 PM", "title": "任务列表测试3", "deadLine": "九月 18, 2017", "fatherTaskId": 45, "implement": [{ "id": 0, "account": "18906414271", "passwd": "123456", "name": "张金钊", "teamId": 3, "isManager": 1, "phone": "18906414271", "email": "18906414271@189.cn", "sex": "男" }], "id": 46, "state": 0 }], "completion": 39, "description": "显示当前登录用户任务详情", "emergency": 0, "updateTime": "Sep 5, 2017 10:26:10 PM", "title": "任务列表测试2", "deadLine": "九月 18, 2017", "docs": [{ "id": 108, "taskId": 45, "name": "chinatelecom.png", "path": "/file/2017-09-05/35c7ccb4-f449-41ac-8a76-cf4803ad391c", "updateTime": "Sep 5, 2017 8:38:47 PM", "userId": 0 }], "readers": [{ "id": 41, "account": "15305374705", "passwd": "123456", "name": "陈帅", "teamId": 2, "isManager": 0, "phone": "15305374705", "email": "15305374705@189.cn", "sex": "男" }], "fatherTaskId": 0, "implement": [{ "id": 1, "account": "18906414263", "passwd": "123456", "name": "张金钊", "teamId": 82, "isManager": 0, "phone": "18906414263", "email": "18906414263@189.cn", "sex": "男" }], "id": 45, "state": 0 };
        }

        function renderTaskView() {
            //contacts = { "upTeamId": 0, "cityName": "济南", "name": "山东电信", "id": 100, "cityID": 0, "subTeams": [{ "upTeamId": 100, "cityName": "济南", "name": "省公司", "id": 1, "cityID": 0, "subTeams": [{ "upTeamId": 1, "cityName": "济南", "name": "省网运", "id": 5, "cityID": 0, "subTeams": [] }] }, { "upTeamId": 100, "cityName": "济宁", "name": "济宁", "id": 2, "cityID": 1, "subTeams": [{ "upTeamId": 2, "cityName": "济宁", "name": "济宁市场部", "id": 3, "cityID": 1, "subTeams": [] }, { "upTeamId": 2, "cityName": "济宁", "name": "济宁网运部", "id": 4, "cityID": 1, "subTeams": [] }] }], "users": [{ "id": 0, "account": "sa", "passwd": "123456", "name": "chenshuai", "createTime": "Aug 3, 2017 10:37:59 AM", "teamId": 100, "isManager": 1, "phone": "15305374705", "email": "15305374705@189.cn", "sex": "男 ", "avatar": "1" }, { "id": 1, "account": "sa", "passwd": "123456", "name": "张金钊", "createTime": "Aug 3, 2017 10:37:59 AM", "teamId": 100, "isManager": 1, "phone": "15305374705", "email": "15305374705@189.cn", "sex": "男 ", "avatar": "1" }] };
            var exeUserbook = new userSelector();
            exeUserbook.setData(contacts);
            var rdrUserbook = new userSelector();
            rdrUserbook.setData(contacts);
            progSlider = $("#progSlider").slider({
                formatter: function (value) {
                    return '进度：' + value + '%';
                }
            });
            $("#collapseDescr").on("show.bs.collapse", function () {
                $("#linkDescrEdit").hide();
                $("#tDescr").hide();
                $("#tDescrEditor").text(task.description);
                $("#tDescrEditor").val(task.description);
            });
            $("#collapseDescr").on("shown.bs.collapse", function () {
                $("#tDescrEditor").focus();

            });
            $("#voteManageEditTaskDetailCan").click(function () {
                $("#voteManageEditTaskDetailTextarea").text("");
                $("#voteManageEditTaskDetailTextarea").collapse('hide');
            });
            
            //修改编辑页面 详情修改确认
            $("#voteManageEditTaskDetailCon").click(function () {
                saveDescription($("#voteManageEditTaskDetail").val(), function (data) {
                    if (data.status == 0) {
                        task.description = $("#voteManageEditTaskDetailTextarea").val();
                    }
                    $("#voteManageEditTaskDetailTextarea").collapse('hide');
                })
            });
            //
            
            
            
            $("#voteManageEditTaskDetailTextarea").on("hide.bs.collapse", function () {
                $("#voteManageEditTaskDetailTextarea").val("");
                $("#voteManageEditTaskDescr").show();
                $("#tDescr").html(task.description.replace("\n", "<br />"));
                alert(task.description);
                $("#linkDescrEdit").show();
            });
            
            
            
            $("#tTitle").html(htmlEncode(task.title));
            $("#tDescr").html(htmlEncode(task.description));
            $("#tCreator").html(task.owner.name);
            $("#tDead").html(task.deadLine);
            $("#emerg2").prop("checked", true);
            $("#edit-title-btn").click(function (e) {
                $("#tTitle").html('<input type="text" id="tTitle-text-editor">');
                $("#tTitle-text-editor").val(task.title);
                $("#tTitle-text-editor").focus();
                $("#tTitle-text-editor").blur(function () {
                    var tempTitle = $("#tTitle-text-editor").val();
                    if (tempTitle != "" && tempTitle != task.title) {
                        saveTitle(tempTitle, function (data) {
                            if (data.status == 0) {
                                task.title = tempTitle;
                                $("#tTitle").html(htmlEncode(task.title));
                            }
                        });
                    }
                    $("#tTitle").html(htmlEncode(task.title));
                });
                $("#tTitle-text-editor").keyup(function (e) {
                    if (e.which == 13) {
                        var tempTitle = $("#tTitle-text-editor").val();
                        if (tempTitle != "" && tempTitle != task.title) {
                            saveTitle(tempTitle, function (data) {
                                if (data.status == 0) {
                                    task.title = tempTitle;
                                    $("#tTitle").html(htmlEncode(task.title));
                                }
                            });
                        }
                        $("#tTitle").html(htmlEncode(task.title));
                    }
                });
            });


            renderExecutors();
            renderReaders();
            renderSubTask();
            renderToolbar();
            function renderToolbar() {
                $("#btn-back-to-tasklist").click(function (e) {
                    e.stopPropagation();
                    loadTaskList();
                });
                //定义删除按键功能
                $("#btn-del-task").click(function (e) {
                    e.stopPropagation();
                    if (!confirm("您确定要删除任务吗？\n删除任务将连同其子任务一并删除，且无法恢复！"))
                        return;
                    var op = createOperation('delTask', { taskId: task.id });
                    getJsonSync(op, function (data) {

                        if (data.status == 0) {
                            loadTaskList();
                        }
                        else warn(data.message);
                    }, function (status, err) {
                        warn("请求失败：" + status + "\n错误：" + JSON.stringify(err));
                    });
                });
            }

            function renderExecutors() {
                drawExeList();
                $("#addExeDiv").click(function (e) {
                    e.stopPropagation();
                });
                $("#btn-exe-add").click(function (e) {
                    e.stopPropagation();
                    $("#addRdrDiv").hide();
                    exeUserbook.setSelectedUsers(getTaskImpUserIds());
                    exeUserbook.setUserTree('addExeNotebook');
                    exeUserbook.setMultiSelect(true);
                    exeUserbook.onNodeSelected = function (ev, node) {
                        addExecutor(node.id, function (data) {
                            if (data.status == 0) {
                                //TODO
                                addImpToTask({ id: node.id, name: node.text });
                                drawExeList();
                            }
                        }, function (status, err) {
                            warn(status + "\n" + err);
                        });
                    }
                    exeUserbook.onNodeUnselected = function (ev, node) {
                        delExecutor(node.id, function (data) {
                            if (data.status == 0) {
                                removeImpFromTask(node.id);
                                drawExeList();
                            }
                        }, function (status, err) {
                            warn(status + "\n" + err);
                        })
                    }
                    exeUserbook.show();
                    $("#addExeDiv").show();
                });
            }



            function renderReaders() {
                drawRdrList();
                $("#addRdrDiv").click(function (e) {
                    e.stopPropagation();
                });
                $("#btn-rdr-add").click(function (e) {
                    e.stopPropagation();
                    $("#addExeDiv").hide();
                    rdrUserbook.setSelectedUsers(getTaskRdrUserIds());
                    rdrUserbook.setUserTree('addRdrNotebook');
                    rdrUserbook.setMultiSelect(true);
                    rdrUserbook.onNodeSelected = function (ev, node) {
                        addReader(node.id, function (data) {
                            if (data.status == 0) {
                                addRdrToTask({ id: node.id, name: node.text });
                                drawRdrList();
                            }
                        }, function (status, err) {
                            warn(status + "\n" + err);
                        });
                    }
                    rdrUserbook.onNodeUnselected = function (ev, node) {
                        delReader(node.id, function (data) {
                            if (data.status == 0) {
                                removeRdrFromTask(node.id);
                                drawRdrList();
                            }
                        }, function (status, err) {
                            warn(status + "\n" + err);
                        });
                    }
                    rdrUserbook.show();
                    $("#addRdrDiv").show();
                });
            }

            function drawRdrList() {
                var rdrListStr = "";
                for (var i in task.readers) {
                    rdrListStr += '<span class="fa fa-close rdrDel" data-del-uid="' + task.readers[i].id + '"></span><span class="fa fa-user taskReader"></span>' + task.readers[i].name;
                }
                $("#readerDiv").html(rdrListStr);
                $(".rdrDel").click(function () {
                    var uid = $(this).data("del-uid");
                    delReader(uid, function (data) {
                        if (data.status == 0) {
                            removeRdrFromTask(uid);
                            drawRdrList();
                        }
                    }, function (status, err) {
                        warn(status + "\n" + err);
                    });
                });
            }
            function drawExeList() {
                var impListStr = "";
                for (var i in task.implement) {
                    impListStr += '<span class="fa fa-close exeDel" data-del-uid="' + task.implement[i].id + '"></span><span class="fa fa-user taskExecutor"></span>' + task.implement[i].name;
                }
                $("#executorDiv").html(impListStr);
                $(".exeDel").click(function () {
                    var uid = $(this).data("del-uid");
                    delExecutor(uid, function (data) {
                        if (data.status == 0) {
                            removeImpFromTask(uid);
                            drawExeList();
                        }
                    },function(status,err){
                        warn(status+"\n"+err);
                    });
                });
            }
            function renderSubTask() {
                var subtaskStr = "";
                for (var i in task.subTaskList) {
                    subtaskStr += '<div class="task-item" data-tid="' + task.subTaskList[i].id + '"><div class="task-item-wrapper"><div class="progress task-cell-progress" style="margin-bottom:0;height:16px"><div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="' + task.subTaskList[i].completion + '" aria-valuemin="0" aria-valuemax="100" style="line-height:16px;height:16px;width: ' + task.subTaskList[i].completion + '%;">' + task.subTaskList[i].completion + '%</div></div><div class="task-cell-title">' + task.subTaskList[i].title + '</div><div class="task-cell-metadata">' + task.subTaskList[i].owner.name + '</div></div></div>';
                }
                $(".subtask-list").html(subtaskStr);
                $(".task-item").click(function (e) {
                    e.stopPropagation();
                    showTaskDetail($(this).data('tid'));
                })
            }

            //标题旁边的完成checkbox状态切换事件
            $("#chkCompletion").change(function (e) {
                if ($(this).prop("checked")) {
                    setCompletion(task.id, 1000, function (data) {
                        if (data.status == 0) {
                            task.completion = data.entity.completion;
                            progSlider.slider('setValue', task.completion > 100 ? 100 : task.completion, false, false);
                        }
                    });
                } else {

                }
            });

            //设置任务完成度的进度条初始值和改变后的事件
            progSlider.slider('setValue', task.completion > 100 ? 100 : task.completion, false, false);
            progSlider.on("slideStop", function (ev) {
                setCompletion(tId, ev.value, function (data) {
                    if (data.status == 0) {
                        task.completion = data.entity.completion;
                        if (task.completion >= 100)
                            $("#chkCompletion").prop('checked', true);
                        else
                            $("#chkCompletion").prop('checked', false);
                    }
                });
            });
        }

        function saveTitle(title, callback, errCallback) {
            //callback({status:0});
            var op = createOperation('setTaskTitle', { taskId: task.id, title: title });
            getJson(op, callback, errCallback);
        }
        function saveDescription(text, callback, errCallback) {
            //callback({ status: 0 });
            var op = createOperation('setTaskDesc', { taskId: task.id, description: text });
            getJson(op, callback, errCallback);
        }
        function setEmergency(value, callback, errCallback) {
            var op = createOperation('setEmergency', { taskId: task.id, emergency: value });
            getJson(op, callback, errCallback);
        }
        function delExecutor(uid, callback, errCallback) {
            //callback({ status: 0 });
            var op = createOperation('setTaskImp', { taskId: task.id, action: 0, userId: uid });
            getJson(op, callback, errCallback);
        }
        function delReader(uid, callback, errCallback) {
            //callback({ status: 0 });
            var op = createOperation('setTaskReaders', { taskId: task.id, action: 0, userId: uid });
            getJson(op, callback, errCallback);
        }
        function addExecutor(uid, callback, errCallback) {
            //callback({ status: 0 });
            var op = createOperation('setTaskImp', { taskId: task.id, action: 1, userId: uid });
            getJson(op, callback, errCallback);
        }
        function addReader(uid, callback, errCallback) {
            //callback({ status: 0 });
            var op = createOperation('setTaskReaders', { taskId: task.id, action: 1, userId: uid });
            getJson(op, callback, errCallback);
        }
        function removeImpFromTask(uid) {
            for (var i = 0; i < task.implement.length; i++) {
                if (uid == task.implement[i].id) {
                    task.implement.splice(i, 1);
                    return;
                }
            }
        }
        function removeRdrFromTask(uid) {
            for (var i = 0; i < task.readers.length; i++) {
                if (uid == task.readers[i].id) {
                    task.readers.splice(i, 1);
                    return;
                }
            }
        }
        function addImpToTask(u) {
            task.implement.push(u);
        }
        function addRdrToTask(u) {
            task.readers.push(u);
        }
        function getTaskImpUserIds() {
            var ids = new Array();
            if (!task.implement) return ids;
            for (var i = 0; i < task.implement.length; i++) {
                ids.push(task.implement[i].id);
            }
            return ids;
        }
        function getTaskRdrUserIds() {
            var ids = new Array();
            if (!task.readers) return ids;
            for (var i = 0; i < task.readers.length; i++) {
                ids.push(task.readers[i].id);
            }
            return ids;
        }
    });
}